package com.plat.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.plat.dao.IBaseDao;
import com.plat.security.dao.SysAuthoritiesResourcesDao;
import com.plat.security.entity.SysAuthoritiesResources;
import com.plat.service.ISysAuthoritiesResources;

@Service
public class SysAuthoritiesResourcesImpl extends BaseServiceImpl<SysAuthoritiesResources> implements ISysAuthoritiesResources {

    @Autowired
    private SysAuthoritiesResourcesDao dao;

    @Override
    public IBaseDao<SysAuthoritiesResources> getDao() {
        return dao;
    }

    @Override
    public void updateSysAuthoritiesResources(String rolefunctions, String authorityId) throws Exception {
        List<SysAuthoritiesResources> authoris = dao.findBy("authorityId", authorityId);//已有权限的菜单

        for (SysAuthoritiesResources s : authoris) {
            dao.remove(s);
        }

        if (StringUtils.isNotEmpty(rolefunctions)) {
            SysAuthoritiesResources auth = null;
            for (String resourceId : rolefunctions.split(",")) {
                auth = new SysAuthoritiesResources();
                auth.setAuthorityId(authorityId);
                auth.setResourceId(resourceId);
                auth.setEnabled(true);
                Criteria cri = dao.createCriteria();
                cri.add(Restrictions.eq("authorityId", authorityId));
                cri.add(Restrictions.eq("resourceId", resourceId));
                List<SysAuthoritiesResources> auths = cri.list();
                if(auths != null && auths.size() ==0){
                    dao.save(auth);
                }
            }
        }

    }

}
